<template>
  <div class="user-management-container">
    <div class="header">
      <h1>
        <el-icon><User /></el-icon>
        用户管理系统
      </h1>
      <div class="header-actions">
        <el-button type="primary" circle @click="refreshData">
          <el-icon><Refresh /></el-icon>
        </el-button>
      </div>
    </div>

    <div class="search-bar">
      <el-input
          v-model="filters.keyword"
          placeholder="搜索用户名、邮箱或专业..."
          clearable
          @clear="fetchUsers"
          @keyup.enter="fetchUsers"
          style="width: 300px; margin-right: 10px;margin-top: -2px;"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <el-select
          v-model="filters.isAdmin"
          placeholder="管理员状态"
          clearable
          style="width: 150px;"
      >
        <el-option label="管理员" :value="true" />
        <el-option label="普通用户" :value="false" />
      </el-select>

      <el-select
          v-model="filters.professional"
          placeholder="专业筛选"
          clearable
          filterable
          style="width: 200px;"
      >
        <el-option
            v-for="major in majors"
            :key="major.majorId"
            :label="major.majorName"
            :value="major.majorName"
        />
      </el-select>

      <el-button type="primary" @click="fetchUsers">
        <el-icon><Search /></el-icon>
        搜索
      </el-button>
    </div>

    <div class="stats-container">
      <div class="stat-card admin">
        <div class="stat-title">
          <el-icon><UserFilled /></el-icon>
          管理员用户
        </div>
        <div class="stat-value">{{ stats.adminCount }}</div>
        <div class="stat-description">拥有系统管理权限的用户</div>
      </div>

      <div class="stat-card regular">
        <div class="stat-title">
          <el-icon><User /></el-icon>
          普通用户
        </div>
        <div class="stat-value">{{ stats.regularCount }}</div>
        <div class="stat-description">普通注册用户</div>
      </div>

      <div class="stat-card answers">
        <div class="stat-title">
          <el-icon><EditPen /></el-icon>
          平均答题量
        </div>
        <div class="stat-value">{{ stats.avgAnswers.toFixed(1) }}</div>
        <div class="stat-description">每位用户的平均答题数量</div>
      </div>

      <div class="stat-card favorites">
        <div class="stat-title">
          <el-icon><StarFilled /></el-icon>
          平均收藏量
        </div>
        <div class="stat-value">{{ stats.avgFavorites.toFixed(1) }}</div>
        <div class="stat-description">每位用户的平均收藏题目数</div>
      </div>
    </div>

    <div class="user-table-container">
      <el-table
          :data="users"
          v-loading="loading"
          stripe
          style="width: 100%"
      >
        <el-table-column label="用户ID" prop="userId" width="100" />
        <el-table-column label="用户名" prop="username" min-width="150" />
        <el-table-column label="邮箱" prop="email" min-width="200" />
        <el-table-column label="注册时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="专业" min-width="180">
          <template #default="{ row }">
            <el-tag v-if="row.professional" type="info">
              {{ row.professional }}
            </el-tag>
            <span v-else style="color: #999;">未设置</span>
          </template>
        </el-table-column>
        <el-table-column label="管理员状态" width="130" align="center">
          <template #default="{ row }">
            <el-tag :class="['admin-badge', row.isAdmin ? 'admin-true' : 'admin-false']">
              {{ row.isAdmin ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                  :type="row.isAdmin ? 'warning' : 'success'"
                  size="small"
                  @click="toggleAdminStatus(row)"
              >
                {{ row.isAdmin ? '取消管理员' : '设为管理员' }}
              </el-button>

              <el-button
                  type="primary"
                  size="small"
                  @click="showEditDialog(row)"
              >
                <el-icon><Edit /></el-icon>
              </el-button>

              <el-button
                  type="danger"
                  size="small"
                  @click="resetPassword(row)"
              >
                <el-icon><Key /></el-icon>
              </el-button>

              <el-button
                  type="info"
                  size="small"
                  @click="showStatistics(row)"
              >
                <el-icon><DataAnalysis /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-container">
      <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="fetchUsers"
          @current-change="fetchUsers"
      />
    </div>
  </div>

  <!-- 编辑用户对话框 -->
  <el-dialog
      v-model="editDialogVisible"
      :title="'编辑用户：' + currentUser.username"
      width="600px"
  >
    <el-form :model="currentUser" label-width="120px">
      <div class="user-detail-grid">
        <div class="detail-item">
          <div class="detail-label">
            <el-icon><User /></el-icon>
            用户名
          </div>
          <div class="detail-value">{{ currentUser.username }}</div>
        </div>

        <div class="detail-item">
          <div class="detail-label">
            <el-icon><Message /></el-icon>
            邮箱
          </div>
          <div class="detail-value">{{ currentUser.email }}</div>
        </div>

        <div class="detail-item">
          <div class="detail-label">
            <el-icon><Calendar /></el-icon>
            注册时间
          </div>
          <div class="detail-value">{{ formatDate(currentUser.createdAt) }}</div>
        </div>

        <div class="detail-item">
          <div class="detail-label">
            <el-icon><Lock /></el-icon>
            管理员状态
          </div>
          <div class="detail-value">
            <el-switch
                v-model="currentUser.isAdmin"
                active-text="管理员"
                inactive-text="普通用户"
            />
          </div>
        </div>
      </div>

      <el-form-item label="专业信息">
        <el-select
            v-model="currentUser.professional"
            placeholder="选择专业"
            style="width: 100%"
            clearable
            filterable
        >
          <el-option
              v-for="major in majors"
              :key="major.majorId"
              :label="major.majorName"
              :value="major.majorName"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 用户行为统计对话框 -->
  <el-dialog
      v-model="statDialogVisible"
      :title="currentUser.username + ' - 学习行为分析'"
      width="800px"
  >
    <div v-if="currentUser.statistics && currentUser.statistics.totalAnswers > 0">
      <div class="user-detail-grid">
        <div class="detail-item">
          <div class="detail-label">
            <el-icon><EditPen /></el-icon>
            总答题量
          </div>
          <div class="detail-value">
            <el-tag type="success" size="large">
              {{ currentUser.statistics.totalAnswers }}
            </el-tag>
          </div>
        </div>

        <div class="detail-item">
          <div class="detail-label">
            <el-icon><Check /></el-icon>
            正确答题
          </div>
          <div class="detail-value">
            <el-tag type="success" size="large">
              {{ currentUser.statistics.correctAnswers }}
            </el-tag>
          </div>
        </div>

        <div class="detail-item">
          <div class="detail-label">
            <el-icon><Close /></el-icon>
            错误答题
          </div>
          <div class="detail-value">
            <el-tag type="danger" size="large">
              {{ currentUser.statistics.totalAnswers - currentUser.statistics.correctAnswers }}
            </el-tag>
          </div>
        </div>

        <div class="detail-item">
          <div class="detail-label">
            <el-icon><StarFilled /></el-icon>
            收藏题目
          </div>
          <div class="detail-value">
            <el-tag type="warning" size="large">
              {{ currentUser.statistics.favoriteCount }}
            </el-tag>
          </div>
        </div>
      </div>

      <el-divider />

      <h3 style="margin-bottom: 15px;">正确率分析</h3>
      <div class="progress-container">
        <span class="progress-text">综合正确率: {{ currentUser.statistics.correctRate }}%</span>
        <el-progress
            :percentage="currentUser.statistics.correctRate"
            :color="currentUser.statistics.correctRate > 70 ? '#4caf50' :
                  (currentUser.statistics.correctRate > 40 ? '#ff9800' : '#f44336')"
            style="flex: 1;"
        />
      </div>

      <h3 style="margin: 20px 0 15px;">专业领域分析</h3>
      <el-table :data="currentUser.statistics.majorStats" stripe>
        <el-table-column prop="majorName" label="专业" />
        <el-table-column prop="questionCount" label="答题数量" width="120" />
        <el-table-column label="正确率" width="180">
          <template #default="{ row }">
            <el-progress
                :percentage="row.correctRate"
                :color="row.correctRate > 70 ? '#4caf50' :
                      (row.correctRate > 40 ? '#ff9800' : '#f44336')"
                :show-text="true"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div v-else style="text-align: center; padding: 30px; color: #999;">
      <el-icon size="50px"><DataLine /></el-icon>
      <p style="margin-top: 15px;">暂无学习行为数据</p>
    </div>

    <template #footer>
      <el-button type="primary" @click="statDialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import {
  ElMessage,
  ElMessageBox,
  ElIcon,
  ElButton,
  ElInput,
  ElSelect,
  ElOption,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElTag,
  ElProgress,
  ElDialog,
  ElForm,
  ElFormItem,
  ElSwitch,
  ElDivider
} from 'element-plus';
import {
  User,
  Refresh,
  Search,
  UserFilled,
  EditPen,
  StarFilled,
  Edit,
  Key,
  DataAnalysis,
  Message,
  Calendar,
  Lock,
  Check,
  Close,
  DataLine
} from '@element-plus/icons-vue';
import axios from '@/api/server';

// 用户数据
const users = ref([]);
const loading = ref(false);

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 筛选条件
const filters = reactive({
  keyword: '',
  isAdmin: null,
  professional: null
});

// 统计数据
const stats = reactive({
  adminCount: 0,
  regularCount: 0,
  avgAnswers: 0,
  avgFavorites: 0
});

// 专业列表
const majors = ref([]);

// 当前操作用户
const currentUser = ref({
  userId: null,
  username: '',
  email: '',
  createdAt: '',
  isAdmin: false,
  professional: '',
  statistics: null
});

// 对话框控制
const editDialogVisible = ref(false);
const statDialogVisible = ref(false);

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
};

// 刷新所有数据
const refreshData = () => {
  fetchUsers();
  fetchStats();
};

// 获取用户列表
// const fetchUsers = async () => {
//   loading.value = true;
//   try {
//     const params = {
//       pageNum: pagination.currentPage,
//       pageSize: pagination.pageSize,
//       keyword: filters.keyword,
//       isAdmin: filters.isAdmin,
//       professional: filters.professional
//     };
//
//     const response = await axios.get('/admin/manage/users/page', { params });
//     const data = response.data.data;
//
//     users.value = data.list || [];
//     pagination.total = data.total || 0;
//   } catch (error) {
//     ElMessage.error('获取用户列表失败: ' + (error.response?.data?.message || error.message));
//   } finally {
//     loading.value = false;
//   }
// };
const fetchUsers = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      keyword: filters.keyword,
      isAdmin: filters.isAdmin,
      professional: filters.professional
    };

    const response = await axios.get('/admin/manage/users/page', { params });
    console.log('用户分页响应:', response.data); // 添加调试日志

    // 重要：后端返回的数据结构是 { data: { records: [], total: 100 } }
    const pageData = response.data.data;

    users.value = pageData.records || []; // 使用records字段
    pagination.total = pageData.total || 0;
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

// 获取统计数据
const fetchStats = async () => {
  try {
    const response = await axios.get('/admin/manage/users/stats');
    const data = response.data.data;

    stats.adminCount = data.adminCount || 0;
    stats.regularCount = data.regularCount || 0;
    stats.avgAnswers = data.avgAnswers || 0;
    stats.avgFavorites = data.avgFavorites || 0;
  } catch (error) {
    ElMessage.error('获取统计数据失败');
  }
};

// 切换管理员状态
const toggleAdminStatus = async (user) => {
  try {
    await ElMessageBox.confirm(
        `确定要${user.isAdmin ? '取消' : '授予'}用户 "${user.username}" 的管理员权限吗？`,
        '管理员权限变更',
        { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    );

    console.log('请求参数:', {
      userId: user.userId,
      isAdmin: !user.isAdmin
    });

    const response = await axios.put('/admin/manage/users/admin-status', {
      userId: user.userId,
      isAdmin: !user.isAdmin
    });

    console.log('响应数据:', response.data);

    // 使用响应式更新方式
    const index = users.value.findIndex(u => u.userId === user.userId);
    if (index !== -1) {
      // 创建新对象替换原对象，确保响应式更新
      users.value[index] = {
        ...users.value[index],
        isAdmin: !users.value[index].isAdmin
      };
    }

    ElMessage.success(`已${!user.isAdmin ? '授予' : '取消'}管理员权限`);
    fetchStats();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message));
    }
  }
};

// 重置密码
const resetPassword = async (user) => {
  try {
    const { value } = await ElMessageBox.prompt(
        `确定要重置用户 "${user.username}" 的密码吗？`,
        '重置密码',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^.{6,20}$/,
          inputErrorMessage: '密码长度需在6-20个字符之间',
          inputPlaceholder: '输入新密码'
        }
    );

    // 修改为发送JSON请求体
    await axios.put('/admin/manage/users/password', {
      userId: user.userId,
      newPassword: value
    });

    ElMessage.success('密码重置成功');
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('重置密码失败: ' + (error.response?.data?.message || error.message));
    }
  }
};

// 显示编辑对话框
const showEditDialog = (user) => {
  currentUser.value = { ...user };
  editDialogVisible.value = true;
};

// 保存用户信息
const saveUser = async () => {
  try {
    await axios.put('/admin/manage/users', {
      userId: currentUser.value.userId,
      professional: currentUser.value.professional,
      isAdmin: currentUser.value.isAdmin,
      email: currentUser.value.email
    });

    const index = users.value.findIndex(u => u.userId === currentUser.value.userId);
    if (index !== -1) {
      users.value[index] = { ...currentUser.value };
    }

    ElMessage.success('用户信息更新成功');
    editDialogVisible.value = false;
  } catch (error) {
    ElMessage.error('更新失败: ' + (error.response?.data?.message || error.message));
  }
};

// 显示用户行为统计
const showStatistics = async (user) => {
  try {
    currentUser.value = { ...user };
    statDialogVisible.value = true;

    // 从后端获取详细统计信息
    const response = await axios.get(`/admin/manage/users/${user.userId}/statistics`);
    currentUser.value.statistics = response.data.data;
  } catch (error) {
    ElMessage.error('获取用户统计数据失败');
    currentUser.value.statistics = null;
  }
};

// 获取专业列表
const fetchMajors = async () => {
  try {
    const response = await axios.get('/admin/manage/majors');
    majors.value = response.data.data || [];
  } catch (error) {
    ElMessage.error('获取专业列表失败');
    majors.value = [];
  }
};

// 初始化加载数据
onMounted(() => {
  fetchMajors();
  fetchUsers();
  fetchStats();
});
</script>

<style scoped>
/* 保留原有样式，仅做少量优化 */
.user-management-container {
  max-width: 1400px;
  margin: 0 auto;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.header {
  background: linear-gradient(135deg, #1e88e5, #0d47a1);
  color: white;
  padding: 25px 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header h1 {
  font-size: 24px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.header h1 i {
  margin-right: 12px;
  font-size: 28px;
}

.header-actions {
  display: flex;
  gap: 15px;
}

.search-bar {
  background-color: #fff;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.stats-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px;
  background-color: #f9fafc;
  border-bottom: 1px solid #ebeef5;
}

.stat-card {
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-card.admin {
  border-top: 4px solid #ff9800;
}

.stat-card.regular {
  border-top: 4px solid #2196f3;
}

.stat-card.answers {
  border-top: 4px solid #4caf50;
}

.stat-card.favorites {
  border-top: 4px solid #9c27b0;
}

.stat-title {
  font-size: 16px;
  color: #666;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #333;
  margin-bottom: 5px;
}

.stat-description {
  font-size: 14px;
  color: #888;
}

.user-table-container {
  padding: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 20px;
  background-color: #fff;
  border-top: 1px solid #ebeef5;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.admin-badge {
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.admin-true {
  background-color: #ff980020;
  color: #ff9800;
  border: 1px solid #ff980040;
}

.admin-false {
  background-color: #2196f320;
  color: #2196f3;
  border: 1px solid #2196f340;
}

.progress-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.progress-text {
  min-width: 60px;
  font-size: 14px;
  color: #666;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
}

.user-detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.detail-item {
  margin-bottom: 20px;
}

.detail-label {
  font-weight: 600;
  color: #606266;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.detail-value {
  font-size: 16px;
  color: #303133;
  padding: 8px 0;
}

@media (max-width: 768px) {
  .user-detail-grid {
    grid-template-columns: 1fr;
  }

  .stats-container {
    grid-template-columns: 1fr;
  }

  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>